<template>
  <div class="contact-compoment">
    <div class="header-wrapper">
      <div class="header-title">厂商通讯录</div>
      <div v-if="!props.isLook" class="header-btn" @click="addHandle">添加</div>
    </div>
    <div class="data-wrapper">
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          :border="true"
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="companyName" label="联系人公司">
            <template #default="scope">
              <div class="company-name-wrapper">
                <img
                  src="@/assets/images/tongxunlu.png"
                  alt="通讯录"
                  class="company-logo"
                />
                <span class="company-name">{{ scope.row.companyName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="contactName" label="联系人姓名" />
          <el-table-column prop="contactPhone" label="联系人手机号" />
          <el-table-column
            v-if="!props.isLook"
            label="操作"
            width="150"
            align="left"
          >
            <template #default="scope">
              <div class="table-btn" @click="editHandle(scope.row)">编辑</div>
              <div class="table-btn" @click="deleteHandle(scope.row.id)">
                删除
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 添加弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      :title="addForm.id ? '编辑厂商通讯录' : '添加厂商通讯录'"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="姓名" prop="contactName">
          <el-input
            v-model="addForm.contactName"
            placeholder="请输入联系人姓名"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="手机号" prop="contactPhone">
          <el-input
            v-model="addForm.contactPhone"
            placeholder="请输入联系人手机号"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="公司" prop="companyName">
          <el-input
            v-model="addForm.companyName"
            placeholder="请输入联系人公司"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, defineProps } from "vue";
import { useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getVendorContactsByDeviceIdAPI,
  addVendorContactAPI,
  deleteVendorContactAPI,
  ContactType,
} from "@/api/service/contact";

const route = useRoute();
const deviceId = route.query.id as string;

const props = defineProps<{
  isLook: boolean;
}>();

// 表格数据
const tableData = ref<ContactType[]>([]);
// API调用保护状态
const listApiLoading = ref(false);
function getContactList() {
  // 防止并发调用
  if (listApiLoading.value) return;
  listApiLoading.value = true;

  getVendorContactsByDeviceIdAPI(deviceId)
    .then((_data: any) => {
      const data = _data as ContactType[];
      tableData.value = data;
    })
    .catch(() => {
      ElMessage.error("获取厂商通讯录失败");
    })
    .finally(() => {
      listApiLoading.value = false;
    });
}
getContactList();

// 添加厂商通讯录
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);
const addForm = ref({
  id: "",
  companyName: "",
  contactName: "",
  contactPhone: "",
});

function addHandle() {
  addDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑厂商通讯录
function editHandle(row: ContactType) {
  addDialogVisible.value = true;
  addForm.value = {
    id: row.id,
    companyName: row.companyName,
    contactName: row.contactName,
    contactPhone: row.contactPhone,
  };
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const addFormRules = {
  contactName: [
    { required: true, message: "请输入联系人姓名", trigger: "blur" },
  ],
  companyName: [
    { required: true, message: "请输入联系人公司", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系人手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号格式",
      trigger: "blur"
    },
  ],
};

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    id: "",
    companyName: "",
    contactName: "",
    contactPhone: "",
  };
  addFormRef.value?.clearValidate();
}

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      addFormLoading.value = true;
      addVendorContactAPI({
        id: addForm.value.id,
        companyName: addForm.value.companyName,
        contactName: addForm.value.contactName,
        contactPhone: addForm.value.contactPhone,
        deviceId: deviceId,
      })
        .then(() => {
          ElMessage.success(
            addForm.value.id ? "编辑厂商通讯录成功" : "添加厂商通讯录成功"
          );
          addDialogVisible.value = false;
          resetAddForm();
          // 刷新列表
          getContactList();
        })
        .catch(({ message }) => {
          ElMessage.error(message);
        })
        .finally(() => {
          addFormLoading.value = false;
        });
    }
  });
}

// 删除厂商通讯录
function deleteHandle(id: string) {
  ElMessageBox.confirm("确定删除该厂商通讯录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteVendorContactAPI(id)
      .then(() => {
        ElMessage.success("删除厂商通讯录成功");
        getContactList();
      })
      .catch(() => {
        ElMessage.error("删除厂商通讯录失败");
      });
  });
}
</script>

<style scoped lang="scss">
.contact-compoment {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1.5rem;
  background-color: $bg-color-page;
  border-bottom: 1px solid $border-color-primary;
  .header-title {
    font-size: $font-size-page-menu;
    font-weight: 600;
    color: $text-color-regular;
    padding-left: 12px;
    border-left: 4px solid $color_brand;
  }
  .header-btn {
    display: inline-flex;
    align-items: center;
    padding: 0.2rem 1rem;
    color: $text-color-regular;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
    background: $bg-td-2-color;
    border-radius: 0.5rem;
  }
  .header-btn:hover {
    text-decoration: underline;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    padding: 0 0;
    flex: 1;
    min-height: 0;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    color: $text-color-regular;
    margin-left: 1rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .company-name-wrapper {
    display: flex;
    align-items: center;
    .company-logo {
      width: 2rem;
      height: 2rem;
      margin-right: 1rem;
    }
  }
  .company-name {
    font-size: $font-size-base-btn-text;
    color: $text-color-primary;
  }
}
</style>
